package com.mrzhou.auth.service;

import com.mrzhou.auth.authorzation.IntegrationAuthenticationService;
import com.mrzhou.auth.exception.IntegrationException;
import com.mrzhou.auth.support.IntegrationAuthenticationContext;
import com.mrzhou.auth.support.IntegrationAuthenticationEntity;
import com.mrzhou.auth.utils.TokenUtil;
import com.mrzhou.core.tool.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 *  自定义登录的业务处理逻辑
 */
@Component
public class IntegrationUserDetailsImpl implements UserDetailsService {

    private List<IntegrationAuthenticationService> integrationAuthenticationServiceList;

    @Autowired(required = false)
    public void setIntegrationAuthenticationServiceList(List<IntegrationAuthenticationService> authServiceList){
        this.integrationAuthenticationServiceList = authServiceList;
    }

    @Override
    public CloudUserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 从上下文中获取请求中携带的参数
        IntegrationAuthenticationEntity authEntity = IntegrationAuthenticationContext.get();

        // 检查是否是集成登录
        if(null == authEntity) {
            authEntity = new IntegrationAuthenticationEntity();
        }

        // 登录是去除tenantId的校验, 暂不实现此功能
        // 获取用户的租户信息, 目前通过header或param中获取
//        String headerTenantId = authEntity.getAuthHeaderValue(TokenUtil.HEADER_TENANT_ID);
//        String paramTenantId = authEntity.getAuthParameter(TokenUtil.TENANT_ID_PARAM);
//        String tenantId = headerTenantId == null ? paramTenantId : headerTenantId;
//        if(StringUtil.isBlank(tenantId)) {
//            throw new IntegrationException("用户的租户id不能为空！");
//        }
//        authEntity.setTenantId(tenantId);
        authEntity.setUsername(s);
        return this.authentication(authEntity);
    }

    /**
     *  根据不同的登录方式选择对应的业务处理逻辑
     */
    private CloudUserDetails authentication(IntegrationAuthenticationEntity authEntity) throws AuthenticationException {
        if(this.integrationAuthenticationServiceList != null) {
            for(IntegrationAuthenticationService service: integrationAuthenticationServiceList) {
                if(service.support(authEntity)) {
                    return service.authentication(authEntity);
                }
            }
        }
        throw new BadCredentialsException("【" + authEntity.getAuthType() + "】的登录方式未知！");
    }

}
